<?php

namespace app\live\controller;

use app\common\model\live\OnlineModel;
use app\common\model\live\RoomNoticeModel;
use tencentcloud\Im;

class ImController extends BaseController
{

  private $imModel;
  private $onlineModel;
  private $noticeModel;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->imModel = new Im();
    $this->onlineModel = new OnlineModel();
    $this->noticeModel = new RoomNoticeModel();
  }

  /**
   * 获取用户列表
   */
  public function index(){
    $roomId = $this->request->param('room_id/d');
    $list = $this->onlineModel->getList($roomId);
    $this->success('操作成功',null,$list);
  }

  /**
   * 获取在线用户数量
   */
  public function total(){
    $roomId = $this->request->param('room_id/d');
    $total = $this->onlineModel->total($roomId);
    $this->success('操作成功',null,$total);
  }

  /**
   * 获取单个用户资料
   */
  public function info(){
    $roomId = $this->request->param('room_id/d');
    $userId = $this->request->param('user_id/s');
    $info = $this->onlineModel->getInfo($roomId,$userId);
    $this->success('操作成功',null,$info);
  }

  /**
   * 批量设置账号禁言或者取消禁言
   */
  public function forbid()
  {
    $roomId = $this->request->param('room_id/d');
    $userIds = $this->request->param('user_ids/s');
    $shutTime = $this->request->param('shut_time/d',7200); //禁言时间 0标识恢复
    $result = $this->imModel->forbidSendMsg($roomId,$userIds,$shutTime);
    if($result['ErrorCode']>0) abort(500,$result['ErrorInfo']);
    $isForbid = $shutTime>0 ? 1 : 0;
    $this->onlineModel->changeForbid($roomId,$userIds,$isForbid);
    $this->success('操作成功');
  }

  public function changeUser(){
    $data = $this->request->param();
    if($data['filed']=='is_forbid'){
      $shutTime = $data['status']==0?0:86400;
      $result = $this->imModel->forbidSendMsg($data['room_id'],$data['user_ids'],$shutTime);
      if($result['ErrorCode']>0) abort(500,$result['ErrorInfo']);
      $this->onlineModel->changeUser($data['room_id'],$data['user_ids'],$data['filed'],$data['status']);
    }
    if($data['filed']=='is_black'){
      $this->onlineModel->changeUser($data['room_id'],$data['user_ids'],$data['filed'],$data['status']);
    }
    $this->success('操作成功');
  }

  /**
   * 上下线状态变动
   */
  public function online(){
    $roomId = $this->request->param('room_id/d');
    $userIds = $this->request->param('user_ids/s');
    $status = $this->request->param('status/d');
    $this->onlineModel->changeOnline($roomId,$userIds,$status);
    $this->success('操作成功');
  }

  /**
   * 销毁群组
   */
  public function destroy(){
    $roomId = $this->request->param('room_id/d');
    $this->onlineModel->del($roomId);
    $this->imModel->destroyGroup((string)$roomId);
    $this->success('操作成功');
  }

  /**
   * 发布系统公告
   * @throws \Exception
   */
  public function notice(){
    $roomId = $this->request->param('room_id/d');
    $content = $this->request->param('content');
    if(!empty($content)){
      $data['room_id'] = $roomId;
      $data['content'] = $content;
      $this->noticeModel->add($data);
    }else{
      $notice = $this->noticeModel->where("room_id",$roomId)->order('id', 'desc')->find();
      $content = $notice['content'];
    }
    //发送自定义群组消息
    /*$result = $this->imModel->sendGroupMsg($roomId,json_encode([
        'type'=>'notice',
        'option'=>[
            'content'=>$content
        ]],JSON_UNESCAPED_UNICODE)
    );
    if($result['ErrorCode']>0) abort(500,$result['ErrorInfo']);*/
    $this->success('操作成功',$content);
  }


  /**
   * 回调信息收集
   * @throws \Exception
   */
  public function event(){
    $message = json_decode(file_get_contents("php://input"),true);
    trace($message,'debug');
    //发送消息后回调
    if($message['CallbackCommand']=='Group.CallbackAfterSendMsg'){
      $msgBody = $message['MsgBody'][0];
      if($msgBody['MsgType']=='TIMTextElem'){ //聊天信息
        //房间号
        $room_id = $message['GroupId'];
        $textArr = json_decode(htmlspecialchars_decode($msgBody['MsgContent']['Text']),true);
        $data = array(
            'userid'=>$message['From_Account'],
            'avatar'=>$textArr['avatar'] ?? '',
            'nick'=>$textArr['nick'] ?? '',
            'msg'=>$textArr['msg'],
            'identity'=>$textArr['identity'],
            'msg_time'=>$message['MsgTime'],
            'type'=>'liaotian',
        );
        D('live.Chat')->chat($room_id,$data);
        $this->success('操作成功');
      }
    }
    //创建群组后回调
    if($message['CallbackCommand']=='Group.CallbackAfterCreateGroup'){
      //todo
    }
    //解散群组后回调
    if($message['CallbackCommand']=='Group.CallbackAfterGroupDestroyed'){
      //todo
    }
  }

  /**
   * 聊天信息获取
   * @throws \Exception
   */
  public function chatinfo(){
	 $room_id = $this->request->param('room_id/d');
	 $result = D('live.Chat')->chatinfo($room_id,100);
	 return json($result);
  }

}